import { defineStore } from 'pinia'
import { loginApi, getInfoApi } from '@/api/user/user'
import { LoginParm } from '@/api/user/userModel'
import { Result } from '@/http/request'
// 定义类型
export type SuerState = {
  token: string
  userId: string | number
  permissions: string[] //权限
  expireTime: number //过期时间
}
export const userStore = defineStore('userStore', {
  state: (): SuerState => {
    return {
      token: '',
      userId: '',
      permissions: [],
      expireTime: 0
    }
  },
  actions: {
    // 触发方法登录方法
    login(LoginParm: LoginParm) {
      //   <Result> 之所以传;用在方法调用的时候有提示
      return new Promise<Result>((resolve, reject) => {
        loginApi(LoginParm)
          .then((res) => {
            if (res.data.code == 200) {
              console.log('登录成功', res)
              const { token, id, expireTime } = res.data
              this.token = token
              this.userId = id
              this.expireTime = expireTime
            }
            resolve(res)
          })
          .catch((err) => {
            reject(err)
          })
      })
    },
    //   获取用户信息
    getInfo() {
      return new Promise((resolve, reject) => {
        getInfoApi()
          .then((res) => {
            console.log('设置权限信息到vuex里面', res)
            //设置权限信息到vuex里面
            if (res.code == 200) {
              this.permissions = res.data.roles
            }
            resolve(res.data)
          })
          .catch((error) => {
            reject(error)
          })
      })
    }
  },
  // 计算属性
  getters: {},
  persist: {
    enabled: true //开启持久化
  }
})
